package com.qdh.demo1;

import com.qdh.WordCountJob;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;

import java.io.IOException;

public class SplitCountJob {
    /**
     * 测试合并文件
     * @param args
     * @throws IOException
     * @throws InterruptedException
     * @throws ClassNotFoundException
     */
    public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
        //参数非空判断
        if (args.length != 2) {
            System.out.println("参数个数不对");
            System.exit(0);
        }

        // 1. 初始化配置
        Configuration conf = new Configuration();
        conf.set("fs.defaultFS","hdfs://hadoop11:8020");
        //2. 创建job
        Job job = Job.getInstance(conf);
        job.setJarByClass(WordCountJob.class);

        //3. 设置输入格式化工具和输出格式化
        job.setInputFormatClass(TextInputFormat.class);
        job.setOutputFormatClass(TextOutputFormat.class);

        //4. 设置输入路径和输出路径
/*        TextInputFormat.addInputPath(job,new Path("/archive.har"));
        TextOutputFormat.setOutputPath(job,new Path("/out1"));*/
        TextInputFormat.addInputPath(job,new Path(args[0]));
        TextOutputFormat.setOutputPath(job,new Path(args[1]));

        //5. 设置mapper和reducer
        job.setMapperClass(SplitCountMapper.class);
        job.setReducerClass(SplitCountRedoucer.class);

        // 6. 设置mapper的kv类型和reducer的kv类型
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(IntWritable.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);

        // 7. 启动job
        boolean b = job.waitForCompletion(true);
        System.out.println(b);

    }

//局部计算
    static class SplitCountMapper extends Mapper<LongWritable, Text, Text, IntWritable> {

        @Override
        protected void map(LongWritable key, Text value , Context context) throws IOException, InterruptedException {

            String[] split = value.toString().split(" ");
            for (String s : split) {
                context.write(new Text(s.trim()), new IntWritable(1));
            }

        }
    }
//汇总计算（类继承类）
    static class SplitCountRedoucer extends Reducer<Text, IntWritable, Text, IntWritable> {
    @Override
    protected void reduce(Text key, Iterable<IntWritable> values,Context context) throws IOException, InterruptedException {
        //value:张 【1，1，1 ，1】
        int sum = 0;
        for (IntWritable value : values) {
            sum += value.get();
        }
        context.write(key, new IntWritable(sum));

    }
}

}
